/**
 * Created by wm123 on 2017/5/24.
 */
const extend = require('extend');
const Dispatcher = require('./dispatcher');
const Group = require('./group');
const Board = require('./board');
const Messages = require('./messages');

class Game extends Dispatcher {
    constructor(server, room) {
        super();
        this.server = server;
        this.room = room;
        this.groups = this.createGroups();
        this.board = new (this.server.config.Board || Board)(this);
        this.messages = new Messages();
        this.isOver = false;
    }
    createGroups() {
        let regroup = this.server.config.team.regroup;
        if (regroup) {
            regroup = Number(regroup);
            if (this.room.roles.length % regroup !== 0) throw '';
            let groups = [];
            let group = [];
            for (let role of [...this.room.roles].sort(() => Math.random() - 0.5).sort(() => Math.random() - 0.5)) {
                group.push(role);
                if (group.length === regroup) {
                    groups.push(group.splice(0));
                }
            }
            return groups.map((group, index) => new (this.server.config.Group || Group)(this.server, this, index, this.room.teams[index % this.room.teams.length].option, group));
        } else {
            return this.room.teams.map((team, index) => new (this.server.config.Group || Group)(this.server, this, index, team.option, team.roles));
        }
    }
    start() {
        if (this.groups.every(group => group.roles.every(role => role.isReady))) {
            this.groups.forEach(group => group.start());
            console.log(`房间${ this.room.id }所有玩家都已准备好,游戏即将开始`);
            return true;
        } else {
            return false;
        }
    }
    checkWin(groupIndex) {
        if (this.board.isWin(groupIndex)) {
            this.over(groupIndex);
            return true;
        } else {
            return false;
        }
    }
    exit(role) {
        this.groups[role.group].exit(role);
        console.log(`玩家${ role.player.name || role.player.id }中途退出了房间${ this.room.id }的游戏`);
    }
    over(groupIndex = -1) {
        this.groups.forEach((group, index) => group.roles.forEach(role => role.over(typeof groupIndex === 'function' ? groupIndex(group, role) : index === groupIndex, this)));
        this.room.over();
        this.isOver = true;
        console.log(`房间${ this.room.id }游戏结束`);
    }
    message(role, message) {
        this.messages.append({
            group: role.group,
            position: role.position,
            role: role.data,
            message: message
        });
    }
    get summary() {
        return {
            groups: this.groups.map(group => group.data)
        }
    }
    get data() {
        return extend(true, this.summary, {
            board: this.board.data,
            messages: this.messages.data,
        });
    }
}

module.exports = Game;